package com.ruoyi.Controller;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.config.AlipayClientConfig;
import com.ruoyi.domain.Pay;
import com.ruoyi.domain.PaymentVo;
import com.ruoyi.service.AlipayNewService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.net.URI;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@RestController
@RequestMapping("/pay")
@Slf4j
public class PaymentController extends BaseController {
    @Autowired
    private AlipayNewService alipayService;
    @Autowired
    private Environment config;
    @PostMapping("/scanPay")
    public AjaxResult tradePagePay(@RequestBody Pay pay) throws Exception {
        log.info("统一收单下单并支付接口调用");
        String formStr = alipayService.tradeCreate(pay);
        return AjaxResult.success(formStr);
    }
    /**
     * 支付宝回调
     *
     * @param
     * @return
     */
    @PostMapping("/notify")
    public String tradeNotify(HttpServletRequest request) {
        // 转换 ParameterMap 为可修改的 Map<String, String>
        Map<String, String> params = new HashMap<>();
        request.getParameterMap().forEach((key, values) -> {
            if (values != null && values.length > 0) {
                params.put(key, values[0]);
            }
        });

        log.info("支付宝回调参数: {}", params);
        return alipayService.tradeNotify(params);
    }
    @GetMapping(value = "/return")
    public ResponseEntity<Void> returner(HttpServletRequest request) throws AlipayApiException {
        HttpHeaders headers = new HttpHeaders();
        String url = alipayService.tradeReturn(request);
        headers.setLocation(URI.create(url));
        return new ResponseEntity<>(headers, HttpStatus.FOUND);
    }


}
